/**
 * 用于字典维护
 * 数据标准格式:
 *  [{type: '', label: '', value: ''}]
 */

const dic = {
  __cache: {},
  __storeKey: '__dic_key_',
  putAll (typeLabelVal) {
    if (typeof typeLabelVal === 'string' || (typeof typeLabelVal === 'undefined' && typeLabelVal instanceof Array)) {
      localStorage.setItem(this.__storeKey, typeof typeLabelVal === 'string' ? typeLabelVal : JSON.stringify(typeLabelVal))
    }
  },
  query (type) {
    // step1 : 优先从缓存获取; step2: 从本地存储取；
    let labelVal = null
    if (this.__cache[type]) {
      labelVal = this.__cache[type]
    } else {
      const items = localStorage.getItem(this.__storeKey)
      if (items != null) {
        labelVal = JSON.parse(items)
      }
    }
    return labelVal || []
  },
  put (type, labelVal) {
    if (typeof labelVal === 'undefined') {
      labelVal = []
    }
    if (type && (labelVal instanceof Array)) {
      labelVal.forEach(item => {
        item['type'] = type
      })
      this.__cache[type] = labelVal
    }
  },
  clear () {
    this.__cache = {}
    localStorage.removeItem(this.__storeKey)
  },
  remove (type) {
    if (this.__cache[type]) {
      delete this.__cache[type]
    } else {
      // 根据type, 删除多个索引数据，逻辑: 先获取索引,再翻转排序，依次移除
      const items = localStorage.getItem(this.__storeKey)
      if (items != null) {
        const delIndex = []
        const labelVal = JSON.parse(items)
        labelVal.forEach((item, index) => {
          if (item.type === type) {
            delIndex.push(index)
          }
        })
        delIndex.sort((a, b) => {
          return b - a
        })
        delIndex.forEach(index => {
          labelVal.splice(index, 1)
        })
        localStorage.setItem(this.__storeKey, JSON.stringify(labelVal))
      }
    }
  }
}

export default dic
